<template>
  <div  class="wrapper">
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '15px' }" />
    <div style="height:300px">
      <FormPanel
        ref="from"
        :list="initForm"
        :cols="3"
        :formType="value.type"
        :labelWidth="120"
        :isSubmitBtn="false"
        :collapse="false"
        @formChange="changeHandle"
      />
    </div>
    <BreakSpace label="配件信息" :containerStyle="{ marginBottom: '15px' }" />
    <FilterTable
      height="300"
      ref="tablePeij"
      :columns="partColumns"
      :isSelectColumn="isSelectColumn"
      selectionType="single"
      :isMemoryPagination="true"
      :onSyncTableData="syncPjFun"
      :datakey="'records'"
      :isToperInfo="false"
      :onColumnsChange="partColumns => (this.partColumns = partColumns)"
      columnsRef="notification_maintain_info_02"
    >
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="seacherFun(2)">添加配件</el-button>
      </template>
    </FilterTable>

    <!-- 订单选择 -->
    <BaseDialog
      :visible.sync="visiblePartOrder"
      :title="'采购订单查询'"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <orderSelect @close="closeFun(1)" @selectedFun="selectedFun" />
    </BaseDialog>

    <!--配件选择 -->
    <BaseDialog
      title="选择配件"
      :visible.sync="visiblePartsGroup"
      width="1000px"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <partSelect v-model="initData" @close="closeFun(2)" @selectedPartFun="selectedPartFun" />
    </BaseDialog>

    <div class="dialogBottmView">
      <el-button @click="closeDialog('closeDialog')">返 回</el-button>
      <el-button :loading="loadingFlag" @click="saveDialog('50071001')" type="primary">保 存</el-button>
      <el-button :loading="loadingFlag" @click="saveDialog('50071002')" type="primary">提 报</el-button>
    </div>
  </div>
</template>

<script>
import { getFileGroup } from '@/api/partsmanage/common/file';
import { getPartsGroup, postSave } from '@/api/partsmanage/claim/apply';
import { phone} from '@/utils/validate'
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { getCurrentUser } from '@/api/cms-api/origin/construct/dealer';
import orderSelect from './orderSelect'
import partSelect from './partSelect'
export default {
  name: 'chaimapplyinfo',
  mixins: [dictionary],
  components:{
    orderSelect,
    partSelect
  },
  props:{
    value: {
      type: Object,
      data: Object,
      required: true
    },
  },
  data() {
    this.saveData=null;
    return {
      type: this.value.type,
      initForm : this.initFormFun(),
      partColumns: this.creatHeaderPartRoleColumns(),
      partList: [],
      isSelectColumn: false,
      initPartData: {},
      visiblePart: false,
      visiblePartOrder: false,
      visiblePartsGroup: false,
      formData:{},
      initData: {},
      claimid: '',
      loadingFlag:false,
    };
  },
  created() {
    this.init(this.value.data)
  },
  methods: {
    async init(data) {
      if(this.type==='edit'){
        this.claimid = data.id
        getPartsGroup({ "spid": this.claimid }).then(response => {
          var list = response.data.records
          if(response.resultCode === 200){
            this.$nextTick(()=>{
              this.$refs.tablePeij.EXECUTE_INSERT(list)
            })
          }
        })
        this.initForm.forEach(x => {
          if (x.fieldName === 'created_time') {
            x.initialValue = moment(data.created_at).format('YYYY-MM-DD HH:mm:ss');
          } else {
            x.initialValue = data[x.fieldName];
          }
        });
        getFileGroup({ "xtdjid": this.claimid, "xtfjlx": "1" }).then(response => {
          var fileList = response.data.records
          this.initForm.forEach(x => {
            if (x.fieldName === 'wayFiles') {
              x.initialValue = fileList
            }
          })
        })
      } else if (this.type==='add') { // 新增是默认当千用户手机号和经办人
        let res = await getCurrentUser({});
        console.info(res.data)
        if (res.data !== null && res.data.userName !== null) {
          let username = res.data.userName
          this.initForm.forEach(x => {
            if (x.fieldName === 'xtczry') {
              x.initialValue = username
            }
          })
        }
      }
    },
    //保存
    async saveDialog(val) {
      this.$refs.from.SUBMIT_FORM();
      if (this.saveData) {
        this.saveData.type = this.type
        this.saveData.xsddzt = val
        this.saveData.partList = this.formData.details
        this.saveData.id = this.claimid
        if (this.saveData.partList === null || this.saveData.partList === undefined || this.saveData.partList === [] || this.saveData.partList.length === 0) {
          this.$notify.error({title: '提示信息',message:'请添加配件'||'保存失败!'});
          return false;
        }else{
          let part = this.saveData.partList.find(item=>Number(item.bsspsl)<=0)
          if (part){
            this.$notify.error({title: '提示信息',message:'配件信息第'+Number(part.index+1)+'行索赔数量不能为0'});
            return false;
          }
        }
        this.loadingFlag = true;
        let res=await postSave(this.saveData)
        if (res.resultCode === 200) {
          this.$notify.success({title: '提示信息',message:'保存成功!'});
          this.loadingFlag = false;
          this.closeDialog('refresh')
        } else {
          this.loadingFlag = true;
          this.$notify.error({title: '提示信息',message:res.errMsg||'保存失败!'});
        }
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', {visible: false, type: type});
    },
    initFormFun(){
      return [
        {
          type: 'SELECT',
          label: '索赔类型',
          fieldName: 'bssplx',
          placeholder: '请选择',
          initialValue: "",
          itemList: this.createDictList('5006'),
          rules: [{
            required: true,
            message: '必填',
            trigger: 'change'
          }]
        },
        {
          type: 'INPUT',
          label: '索赔单号',
          fieldName: 'spddhm',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
        },
        {
          type: 'INPUT',
          label: '创建日期',
          fieldName: 'created_time',
          placeholder: '请输入',
          initialValue:  moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经办人',
          fieldName: 'xtczry',
          placeholder: '请输入',
          initialValue: '',
          rules: [{
            required: true,
            message: '必填',
            trigger: 'blur'
          }]
        },
        {
          type: 'INPUT',
          label: '经办人电话',
          fieldName: 'sprydh',
          placeholder: '请输入',
          initialValue: '',
          rules: [{
            required: true,
            message: '必填',
            trigger: 'blur'
          },
          { trigger: 'blur', validator: phone }]
        },
        {
          type: 'INPUT',
          label: '采购单号',
          fieldName: 'cgddhm',
          placeholder: '请输入',
          initialValue: '',
          readonly:true,
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun(1)}></el-button>
              </div>
            );
          },
          rules: [{
            required: true,
            message: '必填',
            trigger: 'blur'
          }]
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'bsspbz',
          placeholder: '请输入',
          selfCols:3
        },
        {
          selfCols: 3,
          type: 'UPLOAD_FILE',
          label: '上传文件',
          fieldName: 'wayFiles',
          placeholder: '上传文件...',
          rules: [{ required: true, message: '请上传文件', trigger: 'change' }],
          // initialValue: [{ name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100' }],
          initialValue: '',
          upload: {
            actionUrl: '/api/file/oss/upload',
            limit: 2,
            tipText: '（支持：PDF、RAR、JPG格式）'
          }
        }
      ]
    },
    changeHandle(val){
      this.saveData=val
    },
    creatHeaderPartRoleColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.deletePart(props.row,props.$index)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        { title: '采购单号', dataIndex: 'cgddhm', sorter: true },
        { title: '配件代码', dataIndex: 'bjxmbh', sorter: true },
        { title: '配件名称', dataIndex: 'bjzwmc', sorter: true },
        { title: '仓库', dataIndex: 'bsckmc', sorter: true },
        { title: '采购数量', dataIndex: 'bstxsl', sorter: true },
        {
          title: '索赔数量',
          dataIndex: 'bsspsl',
          filter: true,
          filterType: 'input',
          sorter: true,
          editable: true,
          editType: 'number',
          editRequired: true,
          editValidator:(val, row, callback) => {
            if (row.bsspsl > row.yxsl) {
              this.$notify.error({ title: '提示信息', message: '已超过可索赔最大数量(' + row.yxsl + ')' || '操作失败!' });
              row.bsspje = 0
              row.bsspsl = 0
            } else {
              row.bsspje = eval(row.jjhdj * row.bsspsl);
            }
          }
          // onChange: (val, row) => {
          //   if (row.bsspsl > row.yxsl) {
          //     this.$notify.error({ title: '提示信息', message: '已超过可索赔最大数量(' + row.yxsl + ')' || '操作失败!' });
          //     row.bsspje = 0
          //     row.bsspsl = 0
          //   } else {
          //     row.bsspje = eval(row.jjhdj * row.bsspsl);
          //   }
          // },
          // onInput: (val, row) => {
          //   if (row.bsspsl > row.yxsl) {
          //     this.$notify.error({ title: '提示信息', message: '已超过可索赔最大数量(' + row.yxsl + ')' || '操作失败!' });
          //     row.bsspje = 0
          //     row.bsspsl = 0
          //   } else {
          //     row.bsspje = eval(row.jjhdj * row.bsspsl);
          //   }
          // },
         },
        { title: '采购单价', dataIndex: 'xsxsdj', sorter: true },
        { title: '折扣率', dataIndex: 'pjzkl', sorter: true },
        { title: '加收管理费率', dataIndex: 'jsglfl', sorter: true },
        // { title: '加价率', dataIndex: 'text9', sorter: true },
        { title: '加价后单价', dataIndex: 'jjhdj', sorter: true },
        { title: '采购金额', dataIndex: 'xsysje', sorter: true },
        { title: '索赔金额', dataIndex: 'bsspje', sorter: true },
        { title: '配件属性', dataIndex: 'bjpjsx', sorter: true, render: props => { return <span>{this.createDictText(props.row.bjpjsx, '5000')}</span>; } }
      ];
    },
    deletePart(row,index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        this.$refs.tablePeij.EXECUTE_DELETE([row])
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    closeFun(val) {
      if (val === 1) { // 查询采购单号
        this.visiblePartOrder = false
      } else if (val === 2) { // 查询配件
        this.visiblePartsGroup = false;
      }
    },
    seacherFun(val) {
      if (val === 1) { // 查询采购单号
        this.visiblePartOrder = true;
      } else if (val === 2) { // 查询配件
        var flag = false;
        var xsddhm;
        this.initForm.forEach(x => {
          if (x.fieldName === 'cgddhm') {
            if (x.initialValue === '' || x.initialValue === null || x.initialValue === undefined) {
              flag = true;
            } else {
              xsddhm = x.initialValue
            }
          }
        });
        if (flag) {
          this.$notify.error({ title: '提示信息', message: '请先选择采购订单' || '操作失败!' });
          return false;
        }
        var spid;
        if (this.type==='edit') {
          spid = this.value.data.id
        } else {
          spid = -1
        }
        this.initData =  {
          xsddhm: xsddhm,
          spid:spid,
          id:1001
        };
        this.visiblePartsGroup = true;
      }
    },
    selectedFun(val){
      this.initForm.forEach(x => {
        if (x.fieldName === 'cgddhm') {
          x.initialValue = val[0].xsddhm
        }
      });
      this.visiblePartOrder = false
    },
    selectedPartFun(val) {
      val.forEach(x => {
        x.flag = true
        this.formData.details.forEach(item => {
          if (item.partInfoId === x.partInfoId) {
            x.flag = false
          }
        })
      })
      val.forEach(x => {
        x.bsspsl = 0
        x.bsspje = 0
        x.cgddhm = x.xsddhm
        // Object.assign({
        //   bsspsl: 0,
        //   bsspje: 0,
        //   cgddhm: x.xsddhm
        // }, x)
        if (x.flag === true) {
          this.$refs.tablePeij.EXECUTE_INSERT(x)
        }
      })
      this.visiblePartsGroup = false;
    },
    syncPjFun(details){
      this.formData.details = details
    }
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
